import React, { useEffect } from 'react'
import { useDispatch, useSelector } from 'react-redux'
import avatar from '../assets/back.jpg'
import { RootState } from '../store'
import { getArticle } from '../store/actions/article'
export default function NewsList () {
  const dispatch = useDispatch()
  // 获取当前的选择的频道id
  const id = useSelector((state:RootState) => {
    // 当前频道的下标
    const { index, channels } = state.channel
    if (channels.length > 0) {
      // state.channel.channels: [{id:,name}, {id:, name}, .... ]
      return channels[index].id
    }
  })

  // id的变化会重发请求
  useEffect(() => {
    if (id !== undefined) {
      dispatch(getArticle(id))
    }
  }, [dispatch, id])

  const articleList = useSelector((state:RootState) => state.article)
  return (
    <div className="list">
      {
        articleList.map(it => (<div key={it.art_id} className="article_item">
        <h3 className="van-ellipsis">{it.title}</h3>
        <div className="img_box">
          <img src={it.cover.type ? it.cover.images[0] : avatar} className="w100" alt="" />
        </div>
        <div className="info_box">
          <span>{it.aut_name}</span>
          <span>{it.comm_count}评论</span>
          <span>{it.pubdate}</span>
        </div>
      </div>))
      }
    </div>
  )
}
